package cn.sxw.android.base.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

/**
 * Created by ZengCS on 2018/12/21.
 * E-mail:zcs@sxw.cn
 * Add:成都市天府软件园E3-3F
 */
object BitmapUtils {
    /**
     * 保存Bitmap到SDCard
     *
     * @param bitmap
     * @param filePath 图片保存路径
     */
    @JvmStatic
    fun saveBitmap(bitmap: Bitmap?, filePath: String?, quality: Int): Boolean {
        val success: Boolean
        val file = File(filePath)
        if (file.exists()) {
            val delete = file.delete()
            if (delete) {
                JLogUtil.d("旧文件已删除")
            }
        }
        val dir = file.parentFile
        if (!dir.exists()) {
            val mkdirs = dir.mkdirs()
            if (!mkdirs) {
                return false
            }
        }
        success = try {
            val out = FileOutputStream(file)
            if (bitmap != null && !bitmap.isRecycled) bitmap.compress(
                Bitmap.CompressFormat.JPEG,
                quality,
                out
            )
            out.flush()
            out.close()
            true
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            false
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }
        return success
    }

    /**
     * 保存Bitmap到SDCard
     *
     * @param bitmap
     */
    fun saveBitmapWithZoom(bitmap: Bitmap, filePath: String?, avatarSize: Int): Boolean {
        val success: Boolean
        val target: Bitmap? = zoomImage(bitmap, avatarSize, avatarSize)
        val file = File(filePath)
        if (file.exists()) {
            file.delete()
        }
        success = try {
            val out = FileOutputStream(file)
            target?.compress(Bitmap.CompressFormat.JPEG, 100, out)
            out.flush()
            out.close()
            true
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            false
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }
        return success
    }

    /**
     * 将图片缩放到指定尺寸
     *
     * @param sourceBitmap 图片源
     * @param newWidth     新的宽度
     * @param newHeight    新的高度
     * @return
     */
    private fun zoomImage(sourceBitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap? {
        // 获取这个图片的宽和高
        val width = sourceBitmap.width.toFloat()
        val height = sourceBitmap.height.toFloat()
        // 创建操作图片用的matrix对象
        val matrix = Matrix()
        // 计算宽高缩放率
        val scaleWidth = newWidth.toFloat() / width
        val scaleHeight = newHeight.toFloat() / height
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight)
        return Bitmap.createBitmap(
            sourceBitmap, 0, 0,
            width.toInt(), height.toInt(), matrix, true
        )
    }

    /**
     * 压缩图片
     *
     * @param filePath
     * @return
     */
    fun compressFile(context: Context?, filePath: String?, angle: Int): Bitmap? {
        val opts = BitmapFactory.Options()
        opts.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filePath, opts)
        val scaleH = opts.outHeight.toFloat() / IScreenUtils.getScreenHeight(context)
        val scaleW = opts.outWidth.toFloat() / IScreenUtils.getScreenWidth(context)
        var scale = scaleH.coerceAtMost(scaleW)
        scale = when {
            scale < 1 -> 1f
            scale < 2 -> 2f
            scale < 4 -> 4f
            scale < 8 -> 8f
            else -> 16f
        }
        opts.inSampleSize = scale.toInt()
        opts.inJustDecodeBounds = false
        var bmp = BitmapFactory.decodeFile(filePath, opts)
        if (angle != 0) {
            // 下面的方法主要作用是把图片转一个角度，也可以放大缩小等
            val m = Matrix()
            val width = bmp.width
            val height = bmp.height
            m.setRotate(angle.toFloat()) // 旋转angle度
            bmp = Bitmap.createBitmap(
                bmp, 0, 0, width, height,
                m, true
            ) // 从新生成图片
        }
        return bmp
    }
}